var skuOptionValueCounter=0;//规格值计数器
//增加规格值
// tableDivId 是规格值所对应的skuOptionTable
// skuOptionValue 是一个JSON对象{id,name,type,value}
function addSkuOptionValue(tableDivId,skuOptionValue){
	var id,name,type,value;
	if(null == skuOptionValue){
		skuOptionValueCounter++;
		id = "new_"+skuOptionValueCounter;//包含new表示新增
		name = "";
		type = "1";
		value = "";
		
	}else{
		id = "_"+skuOptionValue.id;
		name = skuOptionValue.name;
		type = skuOptionValue.type;
		value = skuOptionValue.value;
	}
	var html="";
	html += '<tr height="50" class="skuOptionValueClass" id="skuOptionValue'+id+'">';
	html += '<td><input type="text" id="'+id+'" name="skuOptionValueNames"  value="" class="inputtxt"/></td>';
	html += '<td><span class="select_wrap"><select name="skuOptionValueTypes" class="selecttxt" onchange="changeSkuOptionValueType(this,\''+id+'\')" >';
	html += '<option value="1" '+(type==1?"selected":"")+'>'+__FMT.skuOptionValue_skuOptionValueType_1+'</option>';
	html += '<option value="2" '+(type==2?"selected":"")+'>'+__FMT.skuOptionValue_skuOptionValueType_2+'</option>';
	html += '<option value="3" '+(type==3?"selected":"")+'>'+__FMT.skuOptionValue_skuOptionValueType_3+'</option></select>&nbsp;</span>';
	
	
	html += '<span class="textType input_wrap" style="">';
	if(type == 1)
	{
		html += buildTextWidget(id,value);
	}	
	html += '</span>'	
	
	html += '<span class="colorType choice" style="">';
	if(type == 2)
	{
		html += buildColorPickerWidget(id,value);
	}	
	html += '</span>'	
	
	html += '<span class="pictType " style="">';
	if(type == 3)
	{
		html += buildUploadWidget(id,value);
		
	}	
	html += '</span>';
	html += '</td>'
	html += '<td>';
	html += '<a href="javascript:void(0)" onclick="moveUpSkuOptionValue(this)" name="move_up" class="up"></a>';
	html += '<a href="javascript:void(0)" onclick="moveDownSkuOptionValue(this)" name="move_down" class="down"></a>';
	html += '<a href="javascript:void(0)" onclick="deleteSkuOptionValue(this)" class="del"></a>';
	html += '</td><td></td>';
	
	//start:hidden
	html += '<input type="hidden" name="skuOptionValueIds" id="skuOptionValueId'+id+'" value="skuOptionValueId'+id+'"/>';
	//end:hidden
	html += '</tr>';
	$j('#'+tableDivId).append(html);
	$j('#'+id).val(name);
	
	if(type == 2){
		initColorPicker(id,value);
	}else if(type == 3){
		initUpload("skuOptionValueUrl" + id, "other", "jpg", "", uploadSkuOptionValueImageCallback);
	}
	
	showOptionValueMoveIcons();
	
	
}


//建立upload html
// id,value图片路径
function buildUploadWidget(id,value){
	var html="";
	html += '<span class="sku_wrap">';
	if(null != value){
		html += '<em><b style="background-image: url('+__mediaPath + value+' );"  id="skuOptionValueImage'+id+'" width="20" height="20">&nbsp;</b>';
	}else{
		html += '<em><b style=""  id="skuOptionValueImage'+id+'" width="20" height="20">&nbsp;</b>';
	}	
	html += '</em></span>';
	html += '<div class="input_wrap"><input type="hidden" name="skuOptionValueValues" id="skuOptionValueUrl'+id+'" value="'+((null != value)?value:'')+'"/>&nbsp;';
	html += '<span  style="display:inline-block;padding:3px 0 0;">'+__FMT.skuOptionDetail_imageUpload_tip+'</span></div>';
	return html;
}
//建立文本类型 
function buildTextWidget(id,value){
	var html="";
	html += '<input type="text" id="skuOptionValueText'+id+'" name="skuOptionValueValues"  value="'+((null != value)?value:'')+'" class="inputtxt"/> ';
	return html;
}

//建立color html
// id,value颜色hex值

function buildColorPickerWidget(id,value){
	if(value == null || value == "")value="000000";
	var html="";
	html += '<input type="hidden" maxlength="6" size="6"  name="skuOptionValueValues" id="skuOptionValueColor'+id+'" value="'+value+'" />'; 
	html += '<div id="customWidget">';
	html += '<div id="colorSelector'+id+'" class="colorSelector2"><div style="background-color: #'+value+'"></div></div>';
	html += '<div id="colorpickerHolder'+id+'" class="colorpickerHolder2"></div></div>'; 
	return html;
}

//改变规格值类型
//selectDOM 是一个select对象,id是SkuOpitonValueId
function changeSkuOptionValueType(selectDOM,id){
	
	var textTypeSpan =  $j(selectDOM).parents('td:first').find(".textType");
	var pictTypeSpan =  $j(selectDOM).parents('td:first').find(".pictType");
	var colorTypeSpan =  $j(selectDOM).parents('td:first').find(".colorType");
	
	textTypeSpan.empty();
	pictTypeSpan.empty();
	colorTypeSpan.empty();
	if(selectDOM.value == 1){
		textTypeSpan.append(buildTextWidget());
	}else if(selectDOM.value == 2){
		colorTypeSpan.append(buildColorPickerWidget(id));
		initColorPicker(id);
		//如果更为颜色类型，必须修改z-index的值，否则上行会遮挡
		showOptionValueMoveIcons();
	}else if(selectDOM.value == 3){
		pictTypeSpan.append(buildUploadWidget(id));
		initUpload("skuOptionValueUrl" + id, "other", "jpg", "", uploadSkuOptionValueImageCallback);
	}
}


//验证函数
function validateAction(){	

	//remove all the red
	$j(".x-form-invalid + img").remove();	
	$j(".x-form-invalid").attr("class","");	
		
	var jSkuOptionValueNames= $j('input[name="skuOptionValueNames"]');
	jSkuOptionValueNames.each(function(index,obj){
		applyValidate(obj,"required,maxlength=20");
	});
	var jSkuOptionValueValues= $j('input[name="skuOptionValueValues"]');
	jSkuOptionValueValues.each(function(index,obj){
		applyValidate(obj,"required");
	});
	return validateSkuOption($j("#skuOptionForm")[0]);
	
}	
/**
*初始化颜色选择器
*/
function initColorPicker(id,value){
	$j('#colorpickerHolder'+id).ColorPicker({
			flat: true,
			color: '#'+value,
			onSubmit: function(hsb, hex, rgb) {
				$j('#colorSelector'+id+' div').css('backgroundColor', '#' + hex);
				$j('#colorSelector'+id).click();
				$j('#skuOptionValueColor'+id).val(hex);
			}
		});
		$j('#colorpickerHolder'+id+' > div').css('position', 'absolute');
		var widt = false;
		$j('#colorSelector'+id).bind('click', function() {
			$j('#colorpickerHolder'+id).stop().css({"top":"-165px","height":"173px"});
			if(!widt){
				$j('#colorpickerHolder'+id).show();
			}else{
				$j('#colorpickerHolder'+id).hide();
			}
			widt = !widt;
		});
}

//提升规格值顺序
//linkDOM 是一个超链接对象
function moveUpSkuOptionValue(linkDOM){
	var me = $j(linkDOM).parents(".skuOptionValueClass");
	var prev = me.prev(".skuOptionValueClass");
	prev.before(me);
	showOptionValueMoveIcons();
}

//降低规格值顺序
//linkDOM 是一个超链接对象
function moveDownSkuOptionValue(linkDOM){
	var me = $j(linkDOM).parents(".skuOptionValueClass");
	var next = me.next(".skuOptionValueClass");
	next.after(me);
	showOptionValueMoveIcons();
}

//删除规格值
//linkDOM 是一个超链接对象
function deleteSkuOptionValue(linkDOM){
	if(confirm(__FMT.skuOptionValueDetail_delete_confirm)){
		var skuOptionValueId = $j(linkDOM).parents('tr.skuOptionValueClass').attr("id");
		if(skuOptionValueId.indexOf("new") == -1){
			//已有规格值需要提交服务器检查
			var url = __ctxPath+"/product/skuOption.html?doAction=deleteSkuOptionValueCheck&skuOptionValueId="+skuOptionValueId.substring("skuOptionValue_".length);
			$j.post(url,null,deleteSkuOptionValueCallback,"json");
			
		}else{
			//成功删除
			$j(linkDOM).parents(".skuOptionValueClass").remove();
			showOptionValueMoveIcons();
		}			
	}	
}

//删除规格值callback
function deleteSkuOptionValueCallback(data){
	if(data.result == 1){
		//成功删除
		$j('#skuOptionValue_'+data.skuOptionValueId).remove();
		showOptionValueMoveIcons();
	}else{
		//已有商品绑定
		jAlert(__FMT.skuOptionValueDetail_delete_false);
	}
}

//刷新规格值上下移动按钮显示
function showOptionValueMoveIcons(){
	$j('.skuOptionValueClass a[name="move_up"]').addClass("up").removeClass("up_gray");
	$j('.skuOptionValueClass a[name="move_down"]').addClass("down").removeClass("down_gray");
	$j('.skuOptionValueClass:first a[name="move_up"]').addClass("up_gray").removeClass("up");
	$j('.skuOptionValueClass:last a[name="move_down"]').addClass("down_gray").removeClass("down");
	
	//必须调整颜色选择器的z高度，否则上一行的会遮住下一行的
	var zIndex = 1000;
	$j('.skuOptionValueClass div[id="customWidget"]').each(function(){
		zIndex++;
		$j(this).css("z-index", zIndex);
	
	});
}

//上传规格值图片成功后的回调函数
function uploadSkuOptionValueImageCallback(mediaUrl, fileInputId){
	$j('#' + fileInputId.replace("Url","Image")).css("background-image","url('"+__mediaPath + mediaUrl+"')");
}


/**
 * 初始化upload控制
 * @param {Object} fileInputId 需上传的Input
 * @param {Object} uploadCategory 上传文件保存的目录
 * @param {Object} supportedSuffixs 支持的后缀，多个逗号隔开，空表示不限制
 * @param {Object} nonsupportedSuffixs不支持的后缀，多个逗号隔开，空表示不限制
 * @param {Object} onCompleteHandler 上传成功后的回调，返回来个参数，一个是上传后的文件路径，另一个是需上传的Input ID
 */
function initUpload(fileInputId, uploadCategory, supportedSuffixs, nonsupportedSuffixs, onCompleteHandler){
	var urlAction = '/dialog/upload.html?uploadCategory=' + uploadCategory + "&fileInputId=" + fileInputId;
	if (onCompleteHandler) 
		urlAction += "&onCompleteHandler=" + onCompleteHandler.toLocaleString().substring(9, onCompleteHandler.toLocaleString().indexOf("("));
	var plugin_upload_valid = true;
	$j("<input type='button' class='upload_img_3' />").insertAfter("#" + fileInputId).upload({
		name: 'file',
		action: __ctxPath + urlAction,
		enctype: 'multipart/form-data',
		params: {},
		onSubmit: function(){
			return plugin_upload_valid;
		},
		onComplete: function(){
		},
		onSelect: function(){
			plugin_upload_valid = true;
			var idx = this.filename().lastIndexOf(".");
			if (idx == -1 || idx >= this.filename().length) {
				plugin_upload_valid = false;
			}
			var suffix = this.filename().substring(idx + 1, this.filename().length).toLowerCase();
			if (plugin_upload_valid && supportedSuffixs) {
				plugin_upload_valid = (supportedSuffixs.toString().indexOf(suffix) >= 0);
			}
			if (plugin_upload_valid && nonsupportedSuffixs) {
				plugin_upload_valid = (nonsupportedSuffixs.toString().indexOf(suffix) == -1);
			}
			if (!plugin_upload_valid) {
				alert(__FMT.error_upload_unsupport + ":" + supportedSuffixs.toString());
				return false;
			}
		},
		autoSubmit: true
	});
	$j("#" + fileInputId).wrap("<div style='float:left;'></div>");
}